package net.wanho.zx.zx_cms.controller;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.StringReader;
import java.io.Writer;
import java.util.Map;
import javax.annotation.Resource;
import javax.jms.Topic;
import javax.servlet.http.HttpServletResponse;
import net.wanho.zx.pojo.cms.CmsConfig;
import net.wanho.zx.pojo.cms.CmsPage;
import net.wanho.zx.pojo.cms.CmsTemplate;
import net.wanho.zx.zx_cms.service.CmsService;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CmsPageController {
    @Resource
    CmsService cmsService;

    @Resource
    Topic topic;

    @Resource
    public JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    RestTemplate restTemplate;

    @Resource
    GridFsTemplate gridFsTemplate;

    @Resource
    GridFSBucket gridFSBucket;

    //查询显示页面
    @GetMapping({"/cms/page/list"})
    public Page<CmsPage> queryPages(@RequestParam(value = "page", required = false) int pagenum, @RequestParam(value = "size", required = false) int pagesize, @RequestParam(value = "siteId", required = false) String siteId) {
        return this.cmsService.queryCmsPages(pagenum, pagesize, siteId);
    }

    @GetMapping({"/cms/config/get/{configid}"})
    public CmsConfig getCmsConfig(@PathVariable("configid") String configid) {
        return this.cmsService.getCmsConfigById(configid);
    }

    //查询
    @GetMapping({"/cms/page/get/{pageId}"})
    public CmsPage getPages(@PathVariable("pageId") String pageId) {
        return this.cmsService.getPageById(pageId);
    }

    //添加
    @PostMapping({"/cms/page/add"})
    public JSONObject addPage(@RequestBody CmsPage cmsPage) {
        JSONObject jsonObject = new JSONObject();
        try {
            this.cmsService.addCmspage(cmsPage);
            jsonObject.put("pageId", cmsPage.getPageId());
            jsonObject.put("success", Boolean.valueOf(true));
        } catch (Exception e) {
            jsonObject.put("success", Boolean.valueOf(false));
            e.printStackTrace();
        }
        return jsonObject;
    }

    //生成静态文件
    @PostMapping({"/cms/page/generateHtml/{pageId}"})
    @ResponseBody
    public String gen1(@PathVariable("pageId") String pageId) throws Exception {
        CmsPage cmsPage = this.cmsService.getPageById(pageId);
        CmsTemplate cmsTemplate = this.cmsService.getCmsTemplateById(cmsPage.getTemplateId());
        String templateValue = getTemplateValue(cmsTemplate.getTemplateFileId());
        Template template = new Template("template", new StringReader(templateValue), new Configuration(Configuration.VERSION_2_3_23));
        Map map = getDataFromUrl(cmsPage.getDataUrl());
        Writer writer = new FileWriter(new File(cmsPage.getPagePhysicalPath()));
        template.process(map, writer);
        writer.close();
        return "ok";
    }

    //预览
    @RequestMapping({"/cms/page/preview/{pageId}"})
    public void preview(@PathVariable("pageId") String pageId, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        CmsPage cmsPage = this.cmsService.getPageById(pageId);
        CmsTemplate cmsTemplate = this.cmsService.getCmsTemplateById(cmsPage.getTemplateId());
        String templateValue = getTemplateValue(cmsTemplate.getTemplateFileId());
        Template template = new Template("template", new StringReader(templateValue), new Configuration(Configuration.VERSION_2_3_23));
        Map map = getDataFromUrl(cmsPage.getDataUrl());
        template.process(map, response.getWriter());
    }

    public Map getDataFromUrl(String dataurl) {
        ResponseEntity responseEntity = this.restTemplate.getForEntity(dataurl, Map.class, new Object[0]);
        Map map = (Map)responseEntity.getBody();
        return map;
    }

    //发布
    @PostMapping({"/cms/page/postPage/{pageId}"})
    @ResponseBody
    public JSONObject upload2Gridfs(@PathVariable("pageId") String pageId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        CmsPage cmsPage = this.cmsService.getPageById(pageId);
        String htmlFilePath = cmsPage.getPagePhysicalPath();
        CmsTemplate cmsTemplate = this.cmsService.getCmsTemplateById(cmsPage.getTemplateId());
        File file = new File(htmlFilePath);
        FileInputStream inputStram = new FileInputStream(file);
        ObjectId objectId = this.gridFsTemplate.store(inputStram, "1001", "text");
        String fileId = objectId.toString();
        cmsPage.setHtmlFileId(fileId);
        this.cmsService.upadteCmspage(cmsPage);
        this.jmsMessagingTemplate.convertAndSend(this.topic, pageId);
        jsonObject.put("success", Boolean.valueOf(true));
        return jsonObject;
    }

    public String getTemplateValue(String fileId) throws Exception {
        GridFSFile gridFSFile = this.gridFsTemplate.findOne(Query.query((CriteriaDefinition)Criteria.where("_id").is(fileId)));
        GridFSDownloadStream gridFSDownloadStream = this.gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, (InputStream)gridFSDownloadStream);
        String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
        return s;
    }
}
